<template>
  <div>
    <a-upload 
      list-type="picture" 
      accept="video/*" 
      method="POST" 
      :action="imagesUploadApi" 
      :headers="headers" 
      :fileList="fileList" 
      @change="videoChange">
      <a-button>
        <a-icon type="upload" /> 上传视频
      </a-button>
    </a-upload>
  </div>
</template>

<script>
// uid
const uidGenerator = () => {
  return '-' + parseInt(Math.random() * 10000 + 1, 10);
};
// 文件名
const getFileName = (path) => {
  if (path.lastIndexOf('\\') >= 0) {
    let reg = new RegExp('\\\\', 'g');
    path = path.replace(reg, '/');
  }
  return path.substring(path.lastIndexOf('/') + 1);
};
import { mapGetters } from 'vuex';
export default {
  name: 'JImageUpload',
  data() {
    return {
      headers: {},
      fileList: [],
    };
  },
  computed: {
    ...mapGetters(['imagesUploadApi']),
  },
  props: {
    text: {
      type: String,
      required: false,
      default: '上传',
    },
    value: {
      type: String,
      required: false,
    },
  },
  watch: {
    value(val) {
      console.log('value',val)
      this.initFileList(val);
    },
  },
  created() {
    const token = this.$store.getters.token;
    this.headers = { 'X-Access-Token': token };
  },
  methods: {
    initFileList(paths) {
      console.log('paths',paths)
      if (!paths || paths == '') {
        this.fileList = [];
        return;
      }
      let fileList = [];
      fileList.push({
        uid: uidGenerator(),
        name: getFileName(paths),
        status: 'done',
        url: paths,
        response: {
          status: 'history',
          result: paths,
        },
      });
      this.fileList = fileList;
    },
    // 提交图片
    videoChange(info) {
      console.log(info);
      let fileList = info.fileList;
      if (info.file.status === 'done') {
        if (info.file.response.success) {

          fileList = fileList.map((file) => {
            if (file.response) {
              file.url = file.response.result;
            }
            return file;
          });
        }
        this.$message.success(`${info.file.name} 上传成功!`);
        this.$emit('videoVal',info.file.response.result)
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 上传失败.`);
      } else if (info.file.status === 'removed') {
        this.handleDelete(info.file);
        this.$emit('videoVal','')
      }
      this.fileList = fileList;
    },
    handleDelete(file) {
      // 如有需要新增 删除逻辑
      console.log(file);
    },
  },
  model: {
    prop: 'value',
    event: 'change',
  },
};
</script>

<style scoped>
</style>